package com.cdvtc.fengchao.Servlet;

import com.cdvtc.fengchao.dao.GeneralDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/supplierManagementServlet")
public class SupplierManagementServlet extends HttpServlet {

    private GeneralDao generalDao = new GeneralDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询供应商数据
        List<Map<String, Object>> suppliers = generalDao.getSuppliers();
        System.out.println("查询到的供应商数量: " + suppliers.size());
        request.setAttribute("suppliers", suppliers);

        // 转发到JSP页面
        request.getRequestDispatcher("/admin/suppliers.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if ("add".equals(action)) {
            // 添加供应商
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            int result = generalDao.addSupplier(phone, address);
            if (result > 0) {
                System.out.println("供应商添加成功");
            } else {
                System.out.println("供应商添加失败");
            }
        } else if ("update".equals(action)) {
            // 更新供应商
            int id = Integer.parseInt(request.getParameter("id"));
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            int result = generalDao.updateSupplier(id, phone, address);
            if (result > 0) {
                System.out.println("供应商更新成功");
            } else {
                System.out.println("供应商更新失败");
            }
        } else if ("delete".equals(action)) {
            // 删除供应商
            int id = Integer.parseInt(request.getParameter("id"));
            int result = generalDao.deleteSupplier(id);
            if (result > 0) {
                System.out.println("供应商删除成功");
            } else {
                System.out.println("供应商删除失败");
            }
        }
        response.sendRedirect(request.getContextPath() + "/admin/supplierManagementServlet");
    }
}